package de.hsb.ai.learning;

import jade.domain.DFGUIManagement.GetParents;

import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.hsb.ai.learning.Replay.Listener;
import de.hsb.ai.util.ScotlandJadeGameLogger;
import de.hsb.ai.util.ScotlandJadeGameLogger.Entry;
import de.hsb.ai.util.ScotlandJadeHelper;
import de.hsb.ai.util.map.ScotlandJadeMapHelper;
import de.hsb.ai.util.map.ScotlandJadeMapHelper.ScotlandJadeVertex;

public class WinsAnalyzer implements Listener {
	
	public static final Logger logger = LoggerFactory.getLogger("sy.wins");
	
	private AtomicInteger winCounter;

	public WinsAnalyzer(AtomicInteger winCounter) {
		this.winCounter = winCounter;
	}

	@Override
	public void beforeReplay(Replay replay) {
		// TODO Auto-generated method stub
	}

	@Override
	public void handleEntry(Replay replay, Entry entry) {
		// TODO Auto-generated method stub
	}

	@Override
	public void afterReplay(Replay replay) {
		ListIterator<ScotlandJadeVertex> posIter = replay.getPositions().listIterator();
		ScotlandJadeVertex fugitivePos = posIter.next();
		logger.info("" + replay.getPositions());
		while (posIter.hasNext()) {
			logger.info("checking for win");
			if (fugitivePos.getIndex() == posIter.next().getIndex()) {
				logger.info("found win");
				winCounter.incrementAndGet();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		AtomicInteger winCounter = new AtomicInteger();
		
		String fugitive = null;
		if (args.length >= 1) fugitive = args[0];
		
		int numDetectives = 0;
		if (args.length >= 2) numDetectives = Integer.parseInt(args[1]);
		
		double diameter = ScotlandJadeMapHelper.info.getDiameter();
		logger.debug("diameter: " + diameter);
		
		ExecutorService pool = Executors.newFixedThreadPool(6);
		ScotlandJadeGameLogger gameLogger = ScotlandJadeHelper.createGameLogger(numDetectives, fugitive);
		List<List<Entry>> allEntries = gameLogger.read();
		
		for (List<Entry> entries : allEntries) {
			Replay replay = new Replay(entries);
			replay.addListener(new WinsAnalyzer(winCounter));
			pool.submit(replay);
		}
		
		try {
			pool.awaitTermination(2, TimeUnit.SECONDS);
			logger.info(new StringBuilder("games: ").append(allEntries.size()).append(" wins: ").append(winCounter.get()).toString());
		} catch (InterruptedException e) {
			logger.error("waiting for pool to terminate", e);
		} finally {
			pool.shutdown();
		}
	}

}
